-- UISlimeFoodInfo
-- create by cheny3 Jul/09/2015
-- 冈布奥食物树界面

require "game/ui/form/item/UIItemCompound"

-- UISlimeFoodInfo继承自Layer
UISlimeFoodInfo = class("UISlimeFoodInfo", function()
    return cc.Layer:create();
end);

function UISlimeFoodInfo.create(heroId)
    return UISlimeFoodInfo.new(heroId);
end

-- 声明
local resize;

-- 构造函数
function UISlimeFoodInfo:ctor(heroId)
    -- 初始化
    self:setName("UISlimeFoodInfo");
    local node = cc.CSLoader:createNode("layout/item/SlimeFoodInfo.csb");
    self:addChild(node);
    self.node = node;
    self.heroId = heroId;

    -- 注册事件处理的回调函数
    self:registerEventCallback();

    -- 初始化窗口
    self:initForm();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 初始化窗口
function UISlimeFoodInfo:initForm()
    -- 隐藏食物节点
    for  i = 1, 4 do
        local rank = findChildByName(self.node, "CT/rank" .. i);
        local line = findChildByName(self.node, "CT/line" .. i);
        rank:setVisible(false);
        line:setVisible(false);
    end

    -- 设置冈布奥图像
    local slimeIcon = findChildByName(self.node, "CT/slime_icon");
    local slimePath = getHeroLargeIconPath(self.heroId);
    slimeIcon:loadTexture(slimePath);
    slimeIcon:setScale(0.6);

    -- 设置冈布奥背景
    local slimeBg = findChildByName(self.node, "CT/bg_main");
    slimeBg:loadTexture(slimePath);
    slimeBg:setScale(1.2);
    slimeBg:setOpacity(30);
end

-- 重绘
function UISlimeFoodInfo:redraw()
    -- 载入标题
    local title = findChildByName(self.node, "CT/title");
    local title2 = findChildByName(self.node, "CT/title2");

    -- 获取冈布奥
    local pet = PetM.getMyPet(self.heroId);

    -- 根据冈布奥信息设置标题
    local name = PetM.query(self.heroId, "short_name");
    title:setString(string.format(getLocStr("slime_food"), name));
    title2:setString(string.format(getLocStr("food_compound"), pet:getLevel() - 1, PetM.getPetMaxLevel(pet)));
    TextStyleM.setTitleStyle2(title);
    TextStyleM.setSubheadStyle(title2);

    -- 绘制冈布奥食物
    self:redrawSlimeFood();
end

-- 绘制冈布奥食物
function UISlimeFoodInfo:redrawSlimeFood()
    -- 获取冈布奥
    local pet = PetM.getMyPet(self.heroId);

    local rank = pet:getRank();
    local level = pet:getLevel();
    local feedRecord = pet:getFeedRecord() or {};

    -- 计算可以显示的食物组数
    local num = self:getShowGroup();
    -- 锁的星数
    local starNum = num + 1;

    for i = 1, num do
        local group = findChildByName(self.node, "CT/rank" .. i);
        local line = findChildByName(self.node, "CT/line" .. i);
        group:setVisible(true);
        line:setVisible(true);

        local startNum, endNum;
        if i == 1 then
            startNum = 1;
            endNum = 8;
        else
            startNum = 1 + i * 4;
            endNum = startNum + 3;
        end

        for j = startNum, endNum do
            -- 对应节点
            local pos = group:getChildByName("pos" .. j);

            -- 先移除所有的子节点
            pos:removeAllChildren();

            local needOpacity = false;
            if table.indexOf(feedRecord, j) == -1 then
                needOpacity = true;
            end

            -- 获取食物ID
            local cost = PetM.getFeedCost(self.heroId, j);
            local classId = cost[1][2];
            if classId ~= nil then
                -- 绘制食物
                self:redrawFoodItem(pos, classId, needOpacity, j);
            end
        end
    end

    -- 在下一组的首个位置上放置下一等级冈布奥
    if num < 4 then
        local nextGroup = findChildByName(self.node, "CT/rank" .. tostring(num + 1));
        local posNum = 5 + num * 4;
        local posNode = nextGroup:getChildByName("pos" .. posNum);

        local slimeNode = cc.CSLoader:createNode("layout/combat_stat/CombatStatItem.csb");
        local icon = slimeNode:getChildByName("icon");
        local star = slimeNode:getChildByName("star");

        -- 先移除所有的子节点
        posNode:removeAllChildren();

        -- 隐藏数量和背景
        local bg = slimeNode:getChildByName("bg");
        local num = slimeNode:getChildByName("num");
        bg:setVisible(false);
        num:setVisible(false);

        --local slimePath = getMiddleHeroIconPath(self.heroId);
        local lockPath = "images/ui/hero/lock.png";
        icon:loadTexture(lockPath);
        icon:setScale(0.9);
        -- 翻转
        -- icon:setFlippedX(true);

        local tStar = createStarLayer(starNum, "images/ui/symbol/star_little.png", "center", -0.7);
        if tStar ~= nil then
            star:addChild(tStar);
        end
        -- 星星上移
        star:setPositionY(star:getPositionY() + 10);
        nextGroup:setVisible(true);
        posNode:addChild(slimeNode);

        icon:setTouchEnabled(true);

        icon:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 飘字提示
                AudioM.playFx("button_receive_failed");

                -- 需要通关的关卡ID，根据需要解锁的阶段2\3\4,分别对应第4、6、9关
                local chapterId = 4;
                if starNum == 3 then
                    chapterId = 6;
                elseif starNum > 3 then
                    chapterId = 9;
                end
                alert(string.format(getLocStr("slime_food_open"), DungeonAreaM.query(chapterId, "name")));
            end
        end);
    end
end

-- 绘制每一种食物
function UISlimeFoodInfo:redrawFoodItem(posNode, classId, needOpacity, feedId)
    local itemPath = getItemIconPath(ItemM.query(classId, "icon"));
    local maskPath = "images/ui/hero/mask.png";
    local foodNode = cc.CSLoader:createNode("layout/combat_stat/CombatStatItem.csb");
    local icon = foodNode:getChildByName("icon");
    local star = foodNode:getChildByName("star");

    -- 隐藏数量和背景
    local bg = foodNode:getChildByName("bg");
    local num = foodNode:getChildByName("num");
    bg:setVisible(false);
    num:setVisible(false);

    -- 载入图片
    icon:loadTexture(itemPath);
    bg:loadTexture(maskPath);
    bg:setScale(0.9);

    -- 重复动画相关配置
    local initScale  = 0.9;    -- 初始模型比例
    local transScale = 1.0;   -- 过渡模型比例
    local finalScale = 1.1;    -- 最终模型比例
    local speedCoef =  1.0;    -- 速度系数

    local function playAction(image)
        local upTime    = 0.25;
        local up2Time   = 0.25/speedCoef;
        local scaleUp   = cc.ScaleTo:create(upTime, transScale);
        local scaleUp2  = cc.ScaleTo:create(up2Time, finalScale);

        local seq1 = cc.Sequence:create(scaleUp, scaleUp2);
        local action1 = cc.Spawn:create(seq1);

        -- 2.短暂停顿
        local delayTime = 0.2/speedCoef;
        local delay = cc.DelayTime:create(delayTime);

        -- 3.变小
        local downTime  = 0.25/speedCoef;
        local down2Time = 0.25/speedCoef;
        local scaleDown = cc.ScaleTo:create(downTime, transScale);
        local scaleDown2 = cc.ScaleTo:create(down2Time, initScale);
        local seq2 = cc.Sequence:create(scaleDown, scaleDown2);
        local action2 = cc.Spawn:create(seq2);

        local sequenceNodeAction = cc.Sequence:create(action1, delay, action2);
        image:runAction(cc.RepeatForever:create(sequenceNodeAction));
    end

    if (PetM.isMaterialEnough(self.heroId, "food", feedId) == true or ItemM.getAmount(ME.user, classId) > 0) and needOpacity then
        -- 右上角显示加号
        local addImage = ccui.ImageView:create();
        addImage:loadTexture("images/ui/hero/add3.png");
        addImage:setPosition(cc.p(addImage:getPositionX() + 35, addImage:getPositionY() + 35));
        foodNode:addChild(addImage);
        -- 呼吸动态
        playAction(addImage);
    elseif needOpacity then
        -- 右上角显示问号
        local ifImage = ccui.ImageView:create();
        ifImage:loadTexture("images/ui/hero/if.png");
        ifImage:setPosition(cc.p(ifImage:getPositionX() + 35, ifImage:getPositionY() + 35));
        foodNode:addChild(ifImage);
    end

    -- 是否需要透明
    if needOpacity then
        icon:setOpacity(80);
        bg:setVisible(true);
    end

    -- 显示星星
    local starPath = "images/ui/symbol/star_little.png";
    local rank = ItemM.query(classId, "rank");
    local tStar;

    tStar = createStarLayer(rank, starPath, "center", -0.7);

    if tStar ~= nil then
        star:addChild(tStar);
    end

    -- 星星上移
    star:setPositionY(star:getPositionY() + 15);

    posNode:addChild(foodNode);

    icon:setTouchEnabled(true);

    -- 点击处理
    icon:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if needOpacity then
                local pet = PetM.getMyPet(self.heroId);
                local feedRecord = pet:getFeedRecord() or {};
                if table.indexOf(feedRecord, feedId) ~= -1 then
                    -- 飄字提示
                    alert(getLocStr("feed_already"));
                    AudioM.playFx("button_receive_failed");
                    return;
                end

                -- 如果是链接的冈布奥，不让喂食专属技节点
                if PetM.pauseDungeonLimit(self.heroId) then
                    -- 专属技ID
                    local propId = PropM.getPropId("special_level");
                    -- 对应的属性
                    local props = PetM.getFoodProp(classId) or {};
                    for _, prop in pairs(props) do
                        if prop[1] == propId then
                            -- 不允许喂食专属技
                            alert(getLocStr("lictor_pet_feed_limit"));
                            return;
                        end
                    end
                end

                -- 显示食物详细信息
                local UIItemCompound = UIItemCompound.create(self.heroId, classId, nil, feedId);
                UIMgr.getCurrentScene():addForm(UIItemCompound);
                AudioM.playFx("ui_open1");
            else
                -- 飄字提示
                alert(getLocStr("feed_already"));
                AudioM.playFx("button_receive_failed");
            end
        end
    end);
end

-- 播放属性提升动画
function UISlimeFoodInfo:showAttribUpEffect(feedId)
    if self.isShowDesc ~= true then
        return;
    end

    self:redraw();

    self.isShowDesc = false;

    local function delay()
        local food = PetM.getFeedFood(self.heroId, feedId);
        local props = PetM.getFoodProp(food[2]);
        local effectNode = findChildByName(self.node, "CT");
        for i = 1, #props do
            local function show()
                local prop = props[i];
                local desc = extractString(PropM.getPropDesc(props[i]));
                -- 播放属性提升飘字特效
                playAttribUpEffect3(effectNode, cc.p(0, 50), desc);
            end
            if i == 1 then
                show();
            else
                performWithDelay(self, show, (i - 1) * 0.7);
            end
        end
    end
    performWithDelay(self, delay, 0.5);
end

-- 当前可以显示的组数
function UISlimeFoodInfo:getShowGroup()
    for i = 4, 2, -1 do
        if FeatureItemM.isFeatureOpen("food" .. i) then
            return i;
        end
    end
    return 1;
end

-- 注册点击事件
function UISlimeFoodInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISlimeFoodInfo");
        end
    end
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    AddBackEventHandler(self, btnBack, onBackClick);
end

-- 注册事件处理的回调函数
function UISlimeFoodInfo:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISlimeFoodInfo 界面析构清理");
            -- 显示顶部
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                UIMgr.getCurrentScene().topMenu:setVisible(true);
            end

            -- 显示英雄主界面
            local uiHero = UIMgr.getCurrentScene():getFormByName("UIHeroMain");
            if uiHero ~= nil then
                if self.isLevelUp then
                    uiHero:whenLevelUp({["class_id"] = self.heroId});
                end

                uiHero:show();
            end

            -- 抛出事件
            EventMgr.fire(event.FEED_PET_SHOW_CHANGE, self.heroId);
            -- 移除关注事件
            EventMgr.removeAll("UISlimeFoodInfo");
        elseif ev == "enter" then
            -- 隐藏顶部
            UIMgr.getCurrentScene().topMenu:setVisible(false);

            -- 隐藏英雄主界面
            local uiHero = UIMgr.getCurrentScene():getFormByName("UIHeroMain");
            if uiHero ~= nil then
                uiHero:hide();
            end

            -- 关注英雄升级的事件（喂食成功）
            EventMgr.register("UISlimeFoodInfo", event.PET_LEVEL_UP, function(args)
                self.isLevelUp = true;

                self.isShowDesc = true;
            end);

        end
    end);
end

-- 关闭UIItemCompound时候尝试刷新下
function UISlimeFoodInfo:tryRedraw()
    if self.isShowDesc ~= true then
        self:redraw();
    end
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end
